package com.jhhc.StormSurgeForecast.AstronomicalTide.Util;

import com.jhhc.StormSurgeForecast.AstronomicalTide.Pojo.BDMS_ST_ASTROTD_F;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Pojo.DTO.OutFileData;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Service.BDMS_ST_ASTROTD_FService;
import com.jhhc.StormSurgeForecast.StormSurge.Pojo.FBC.BDMS_FBC_TIDE_HL_F;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class GetInformTxtUtil {

    @Autowired
    private BDMS_ST_ASTROTD_FService bdms_st_astrotd_fService;

    static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    static Calendar calendar = new GregorianCalendar();
    //唯一码
    public  String getUUID() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().substring(0,10);
    }
    public  String getUUID20() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().substring(0,20);
    }
    //写入
    public  void write(String path, String content, String encoding)
            throws IOException {
        File file = new File(path);
        file.delete();
        file.createNewFile();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(file), encoding));
        writer.write(content);
        writer.close();
    }
    //读取
    public  String read(String path, String encoding) throws IOException {
        StringBuilder content = new StringBuilder();
        File file = new File(path);
        System.out.println(path);
        try {
            file.createNewFile();
        }catch (Exception e){
            e.printStackTrace();
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                Files.newInputStream(file.toPath()), encoding));
        String line = null;
        while ((line = reader.readLine()) != null) {
            content.append(line).append("\n");
        }
        reader.close();
        System.out.println("content"+content.toString());
        return content.toString();
    }

    public  List<String> processStrings(String[] strings) {
        List<String> resultList = new ArrayList<>(Arrays.asList(strings));
        resultList.removeIf(s -> s.trim().isEmpty());

        List<String> finalResult = new ArrayList<>();
        for (String s : resultList) {
            if (s.length() > 0) {
                if (s.contains("-")) {
                    String[] parts = s.split("-");
                    finalResult.add(parts[0]);
                    for (int j = 1; j < parts.length; j++) {
                        finalResult.add("-" + parts[j]);
                    }
                } else {
                    finalResult.add(s);
                }
            }
        }
        finalResult.removeIf(s -> s.trim().isEmpty());
        //finalResult.remove(0);
        return finalResult;
    }
    //解析Out
    public  List<OutFileData> GetOUTFileData(String newPath) {
        //  WaterWay.Model.FBC.OUTFileData outFileData = new WaterWay.Model.FBC.OUTFileData();
        List<OutFileData> datas = new ArrayList<>();
        try {
            List<String> fileData = Files.readAllLines(Paths.get(newPath), Charset.forName("GBK"));
            String year ="" ;
            String month ="";
            String day = "";
            fileData.removeIf(String::isEmpty);


            for (int i = 0; i < fileData.size(); i++) {

                if (i == 0) {
                    continue;
                }
                if (fileData.get(i).contains("年")) {
                    year = fileData.get(i).split(" ")[2].trim().substring(0,4);
                    month = fileData.get(i + 1).split(" ")[2].substring(0, 2).trim();
                    i++;
                }else if (" ".equals(fileData.get(i))){
                    continue;
                }
                else if (fileData.get(i).contains("日期")) {
                    continue;
                } else if (fileData.get(i).contains("平均均方差")) {
                    // outFileData.setFangCha(fileData.get(i).split("=")[1].trim());
                    continue;
                } else {
                    String inputString = fileData.get(i);

                    String[] tide = inputString.replaceAll("[\\u4e00-\\u9fa5]+", " ").split(" ");
                    List<String> scList = processStrings(tide);
                    if ( scList.get(0).length()>2){
                        day = scList.get(0).substring(0, 2).trim();
                    }else {
                        day = scList.get(0);
                    }
                    System.out.println(scList);
                    scList.remove(0);
                    List<Double> scdatas = new ArrayList<>();
                    for (String scdata : scList) {
                        scdata =  scdata.replaceAll("\\D", "");
                        scdatas.add(Double.parseDouble(scdata));
                    }
                    String[] twc = fileData.get(i + 1).split(" ");
                    List<String> twcList = processStrings(twc);
                    List<Double> twcdatas = new ArrayList<>();
                    for (String twcdata : twcList) {
                        twcdatas.add(Double.parseDouble(twcdata));
                    }
                    for (int j = 0; j < scdatas.size(); j++) {
                        OutFileData data = new OutFileData();
//                        System.out.println(year);
//                        System.out.println(month);
//                        System.out.println(day);
//                        System.out.println(j);
                        LocalDateTime dateTime = LocalDateTime.of(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day), j, 0, 0);

                        // Define the date time format
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

                        // Format the LocalDateTime object
                        String formattedDateTime = dateTime.format(formatter);
                        data.setTm(formattedDateTime);
                        data.setTdz(scdatas.get(j)/100);
                        data.setTwc(twcdatas.get(j)/100);
                        data.setZs((scdatas.get(j) - twcdatas.get(j))/100);
                        datas.add(data);
                    }
                    i = i + 2;
                }
            }
            if (!datas.isEmpty()) {
                return datas;
            } else {

                return null;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return datas;
        }
    }

//    public static void main(String[] args) {
//        String path ="e:\\23ER.OUT";
//        for (Data data : GetOUTFileData(path)) {
//            System.out.println(data);
//        }
//    }
//    public static void main(String[] args) {
//        try {
//            System.out.println(readToList(getCourseFile()+"\\"+"temp\\"+"edaae5c4-08b7-4c6d-9bab-8d7926cff0ad"+"\\SHTIDEcw.lvl","GBK"));
//        } catch (Exception exception) {
//            exception.printStackTrace();
//        }
//    }

    //获取当前项目存放路径
    public static String getCourseFile(){
        File directory = new File("");//参数为空
        String courseFile = null;
        try {
            courseFile = directory.getCanonicalPath();
        } catch (IOException exception) {
            exception.printStackTrace();
        }
        return  courseFile;
    }
    //创建以方案命名的文件夹
    public boolean mkdirFile(String scheme){
        String courseFile =getCourseFile();
        File file = new File(courseFile+File.separator +"temp"+File.separator +scheme);
        return file.mkdirs();
    }


    //写入inform.txt文件
    public void  getTHFXInformTxt(String modelType,String scheme,String serverType){
        String courseFile =getCourseFile();
        switch (modelType){
            case "TideForecast":
                String filePath = courseFile+File.separator +"temp"+File.separator  +scheme+File.separator +"INFORM.TXT";
                String content = "";
                if ("windows".equals(serverType)) {
                    content = "Y                          做调和分析      \n" +
                            "OBSEPHAR.DAT              用于做调和分析的数据文件名\n" +
                            "N                           潮汐预报\n" +
                            "TIDE                         测站名，现统一成tide                       \n" +
                            "N                            不要重新设定平均海面 \n" +
                            "N                             不要分离增减                             \n" +
                            "N                             输出天文潮   \n+" +
                            "  ";
                }else {
                    content = "Y                            ！ 做调和分析      \n" +
                            "OBSEPHAR.DAT                 ！用于做调和分析的数据文件名\n" +
                            "N                              ! 潮汐预报                 \n" +
                            "       !预报的时间段（起始年、月、日、时,终止的年、月、日、时）\n" +
                            "TIDE                            !测站名，现统一成tide                       \n" +
                            "N                             !不要重新设定平均海面 \n" +
                            "N                             !不要分离增减                             \n" +
                            "Y                             ! 输出天文潮        \n" +
                            "\n";
                }
                try {
                    write(filePath,content,"GBK");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            default:
        }
    }
    //天文潮预报计算
    public void  getTideForecastInformTxt(String modelType,String scheme,String startTime,String endTime,String serverType,String time) throws Exception{

        calendar.setTime( format.parse(endTime));
        calendar.add(Calendar.HOUR,-1);
        String courseFile =getCourseFile();
        if ("TideForecast".equals(modelType)) {
            String filePath = courseFile+File.separator  +"temp"+File.separator  + scheme + File.separator +"INFORM.TXT";
            String content = "";
            if ("windows".equals(serverType)) {
                content = "N                          \n" +
                        "Y                          \n" +
                        getDate(startTime, format.format(calendar.getTime())) + "\n" +
                        time + "HG.RES              \n" +
                        "TIDE\n" +
                        "N                           \n" +
                        "N                                        \n" +
                        "Y";
            } else {
                content = "N\n" +
                        "Y                              ! 潮汐预报               \n" +
                        getDate(startTime, format.format(calendar.getTime()))+"       !预报的时间段（起始年、月、日、时,终止的年、月、日、时）   \n" +
                        time + "HG.RES              \n" +
                        "TIDE   \n" +
                        "N                             !不要重新设定平均海面 \n" +
                        "N                             !不要分离增减                             \n" +
                        "Y                             ! 输出天文潮        \n" +
                        "\n" +
                        "\n" +
                        "\n";
            }
            try {
                write(filePath, content, "UTF-8");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //判断字符串
    public static String getZeroString(String str){
        if (str.charAt(0) == '0'){
            return str.substring(1,2);
        }
        return str;
    }
    //日期
    public  String getDate(String startTime,String endTime){
        String startYear=startTime.substring(0,4);
        String startMonth=getZeroString(startTime.substring(5,7));
        String startDay=getZeroString(startTime.substring(8,10));
        String startHour=getZeroString(startTime.substring(11,13));
        String endYear=endTime.substring(0,4);
        String endMonth=getZeroString(endTime.substring(5,7));
        String endDay=getZeroString(endTime.substring(8,10));
        String endHour=getZeroString(endTime.substring(11,13));
        String date =startYear+","+startMonth+","+startDay+","+startHour+","
                +endYear+","+endMonth+","+endDay+","+endHour;
        return  date;
    }

    //写入实测数据
    public void  getOBSEPHAR(String stcd, String stnm, String startTime,String endTime, List<Integer> tdzs,String modelType,String scheme) {
        String courseFile =getCourseFile();
        switch (modelType){
            case "TideForecast":
                String filePath = courseFile+File.separator +"temp"+File.separator +scheme +File.separator +"OBSEPHAR.DAT";
                String datas = "";
                for (int i=0; i<tdzs.size();i++) {
                    if (i!=0&&i%24==0){
                        datas = datas+ "\n";
                    }
                    String tdz =null;
                    if ((tdzs.get(i)>-100&&tdzs.get(i)<=-10)||tdzs.get(i)>=100){
                        tdz=tdzs.get(i)+" ";
                    }
                    else if ((tdzs.get(i)>-10&&tdzs.get(i)<0)||((tdzs.get(i)>=10&&tdzs.get(i)<100))){
                        tdz=tdzs.get(i)+"  ";
                    } else if (tdzs.get(i)>=0&&tdzs.get(i)<10){
                        tdz=tdzs.get(i)+"   ";
                    } else {
                        tdz= String.valueOf(tdzs.get(i));
                    }
                    datas = datas + "" + tdz+" " ;
                }
                String stationName="'"+stnm+"'";
                String date =getDate(startTime ,endTime);
                String content = stationName+","+date+"\n" +
                        "'obs',"+stcd+","+stationName+" 0 0 0 0\n" +
                        datas;
                try {
                    write(filePath,content,"GBK");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }


    //创建天文潮预报的调和分析常数文件
    public  void  tiedYearRes(String time,String scheme,String content){
        String courseFile =getCourseFile();
        String tide_Year=time+"HG.RES";
        String filePath = courseFile+File.separator +"temp"+File.separator +scheme+File.separator +tide_Year;

        try {
            write(filePath,content,"GBK");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //调用计算程序
    public void execute(String modelType, String scheme) {
        String courseFile = getCourseFile();
        String orig = courseFile + File.separator + "model" + File.separator + modelType + File.separator + "Phar_sh.exe"; //源文件
        String dest = courseFile + File.separator + "temp" + File.separator + scheme;
        String cmd_copy = "cmd /c copy " + orig + " " + dest;
        System.out.println(cmd_copy);
//        String cmd_run = "cmd /c Phar_sh.exe";

        //创建复制Phar_sh.exe文件的ProcessBuilder
        ProcessBuilder copyBuilder = new ProcessBuilder("cmd", "/c", "copy", orig, dest);
        copyBuilder.redirectErrorStream(true);  //将标准输入和标准错误流进行合并

        try {
            Process copyProcess = copyBuilder.start();
            //等待命令执行完毕
            copyProcess.waitFor();

            //打印复制命令执行的输出
            System.out.println("复制命令执行结果：" + getProcessOutput(copyProcess));

            //创建运行Phar_sh.exe的ProcessBuilder
            ProcessBuilder runBuilder = new ProcessBuilder("cmd", "/c", "Phar_sh.exe");
            runBuilder.directory(new File(dest));  //设置运行命令的工作目录

            Process runProcess = runBuilder.start();
            //等待命令执行（此处设置了等待时间为3秒）
            if(runProcess.waitFor(3, TimeUnit.SECONDS)){
                System.out.println("Phar_sh.exe运行结束");
            } else {
                System.out.println("Phar_sh.exe运行超时");
                runProcess.destroy();
            }
            //打印运行命令执行的输出
            System.out.println("Phar_sh.exe命令执行结果：" + getProcessOutput(runProcess));

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("执行结束");
    }

    //辅助方法，用于从Process的InputStream中获取输出结果
    private String getProcessOutput(Process process) throws IOException {
        StringBuilder output = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            output.append(line).append("\n");
        }
        return output.toString();
    }

    public void executeLiunx(String modelType, String scheme) {
        String courseFile = getCourseFile();
        String orig = courseFile + File.separator + "model" + File.separator + modelType + File.separator + "Phar_sh"; // 源文件
        String dest = courseFile + File.separator + "temp" + File.separator + scheme;
        String cmd_copy = "cp -a " + orig + " " + dest;
        String cmd = "cd " + dest + " && chmod +777 Phar_sh && ./Phar_sh";
        // 创建 ProcessBuilder 对象
        ProcessBuilder builder = new ProcessBuilder("sh", "-c", cmd);
        // 设置工作目录
        builder.directory(new File(dest));
        try {
            // 执行复制命令
            Process process_copy = builder.command("sh", "-c", cmd_copy).start();
            process_copy.waitFor(); // 等待复制文件子进程完成
            // 执行命令
            Process process = builder.start();
            process.waitFor(); // 等待执行命令子进程完成
            // 检查进程是否已经结束
            process.destroy();
        } catch (Exception e) {
            e.printStackTrace();
            // 根据实际情况进行异常处理
        }
        System.out.println("运行结束");
    }

    public String executeLiunx28(String modelType, String scheme) {
        StringBuilder result = new StringBuilder(); // 存储执行结果
        String courseFile = getCourseFile();
        String orig = courseFile + File.separator + "model" + File.separator + modelType + File.separator + "Phar_sh"; // 源文件
        String dest = courseFile + File.separator + "temp" + File.separator + scheme;
        String cmd_copy = "cp -a " + orig + " " + dest;

        String cmd = "cd " + dest + " && chmod +777 Phar_sh && ./Phar_sh";
        // 创建 ProcessBuilder 对象
        ProcessBuilder builder = new ProcessBuilder();
        // 设置工作目录
        builder.directory(new File(dest));
        try {
            // 执行复制命令
            Process process_copy = builder.command("sh", "-c", cmd_copy).start();
            //process_copy.waitFor(); // 等待复制文件子进程完成
            result.append(cmd_copy).append("\n");
            result.append("复制命令执行状态").append(process_copy.waitFor()).append("\n");
            // 执行命令
            Process process = builder.command("sh", "-c", cmd).start();
            result.append(cmd).append("\n");
            result.append("运行命令执行状态").append(process.waitFor()).append("\n");
            // 获取执行结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line).append("\n");
            }
            // 检查进程是否已经结束
            process.destroy();
        } catch (Exception e) {
            e.printStackTrace();
            // 根据实际情况进行异常处理
        }
        System.out.println("运行结束");
        return result.toString();
    }
    //读取天文潮文件转成List
    public static List<BDMS_ST_ASTROTD_F> readToList(String path, String encoding) throws Exception {
        List<BDMS_ST_ASTROTD_F>  bdmsStAstrotdFs = new ArrayList<>();
        List<BDMS_ST_ASTROTD_F>  finalDatas = new ArrayList<>();
        File file = new File(path);
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                Files.newInputStream(file.toPath()), encoding));
        String line = null;
        while ((line = reader.readLine()) != null) {
            String [] strings = line.split(",");
            BDMS_ST_ASTROTD_F bdms_st_astrotd_f = new BDMS_ST_ASTROTD_F();
            bdms_st_astrotd_f.setStcd(strings[0]);
            String hour =strings[4].trim();

            if (hour.length()==1){

                hour=" 0"+hour+":00:00";
            }else if (hour.length()==2){
                hour=" "+hour+":00:00";
            }else  if (hour.length()==3){
                hour=" 0"+hour.replace(".",":")+":00";
            }else{
                hour=" "+hour.replace(".",":")+":00";
            }

            String ymdh = format.format( format.parse(strings[1]+"-"+strings[2].trim()+"-"+strings[3].trim()+hour));
            bdms_st_astrotd_f.setYmdh(ymdh);
            double ftdz = Double.parseDouble(strings[5].trim());
            bdms_st_astrotd_f.setFtdz(Double.valueOf(String.format("%.2f",ftdz)));
            bdms_st_astrotd_f.setHltdmk(0);
            bdms_st_astrotd_f.setUnitname(4);
            bdmsStAstrotdFs.add(bdms_st_astrotd_f);
        }
        reader.close();
        List<BDMS_ST_ASTROTD_F> huorbdmsStAstrotdFs = bdmsStAstrotdFs.stream().filter(bdms_st_astrotd_f -> bdms_st_astrotd_f.getYmdh().startsWith("00", 14)).collect(Collectors.toList());
        List<BDMS_ST_ASTROTD_F> gdc_List = bdmsStAstrotdFs.stream().filter(bdms_st_astrotd_f -> !bdms_st_astrotd_f.getYmdh().startsWith("00", 14)).collect(Collectors.toList());
        //根据天分组筛选高低潮
        List<BDMS_FBC_TIDE_HL_F> bdms_fbc_tide_hl_fs = new ArrayList<>();
        Map<String, List<BDMS_ST_ASTROTD_F>> dayListGroup = bdmsStAstrotdFs.stream().collect(Collectors.groupingBy(BDMS_ST_ASTROTD_F::getDay, Collectors.toList()));
        for (Map.Entry<String, List<BDMS_ST_ASTROTD_F>> dayList : dayListGroup.entrySet()) {
            List<BDMS_ST_ASTROTD_F>  gdcbdmsStAstrotdFs = dayList.getValue().stream().filter(bdms_st_astrotd_f -> !bdms_st_astrotd_f.getYmdh().startsWith("00", 14)).collect(Collectors.toList());
            if (gdcbdmsStAstrotdFs.size()>0){
                BDMS_FBC_TIDE_HL_F bdms_fbc_tide_hl_f = new BDMS_FBC_TIDE_HL_F();
                bdms_fbc_tide_hl_f.setTm(format.parse(dayList.getKey()+" 00:00:00"));
                bdms_fbc_tide_hl_f.setFid(4);
                bdms_fbc_tide_hl_f.setStcd(dayList.getValue().get(0).getStcd());
                switch (gdcbdmsStAstrotdFs.size()){
                    case 1:
                        bdms_fbc_tide_hl_f.setT1(format.parse(gdcbdmsStAstrotdFs.get(0).getYmdh()));
                        bdms_fbc_tide_hl_f.setV1(gdcbdmsStAstrotdFs.get(0).getFtdz());
                        break;
                    case 2:
                        bdms_fbc_tide_hl_f.setT1(format.parse(gdcbdmsStAstrotdFs.get(0).getYmdh()));
                        bdms_fbc_tide_hl_f.setV1(gdcbdmsStAstrotdFs.get(0).getFtdz());
                        bdms_fbc_tide_hl_f.setT2(format.parse(gdcbdmsStAstrotdFs.get(1).getYmdh()));
                        bdms_fbc_tide_hl_f.setV2(gdcbdmsStAstrotdFs.get(1).getFtdz());
                        break;
                    case 3:
                        bdms_fbc_tide_hl_f.setT1(format.parse(gdcbdmsStAstrotdFs.get(0).getYmdh()));
                        bdms_fbc_tide_hl_f.setV1(gdcbdmsStAstrotdFs.get(0).getFtdz());
                        bdms_fbc_tide_hl_f.setT2(format.parse(gdcbdmsStAstrotdFs.get(1).getYmdh()));
                        bdms_fbc_tide_hl_f.setV2(gdcbdmsStAstrotdFs.get(1).getFtdz());
                        bdms_fbc_tide_hl_f.setT3(format.parse(gdcbdmsStAstrotdFs.get(2).getYmdh()));
                        bdms_fbc_tide_hl_f.setV3(gdcbdmsStAstrotdFs.get(2).getFtdz());
                        break;
                    case 4:
                        bdms_fbc_tide_hl_f.setT1(format.parse(gdcbdmsStAstrotdFs.get(0).getYmdh()));
                        bdms_fbc_tide_hl_f.setV1(gdcbdmsStAstrotdFs.get(0).getFtdz());
                        bdms_fbc_tide_hl_f.setT2(format.parse(gdcbdmsStAstrotdFs.get(1).getYmdh()));
                        bdms_fbc_tide_hl_f.setV2(gdcbdmsStAstrotdFs.get(1).getFtdz());
                        bdms_fbc_tide_hl_f.setT3(format.parse(gdcbdmsStAstrotdFs.get(2).getYmdh()));
                        bdms_fbc_tide_hl_f.setV3(gdcbdmsStAstrotdFs.get(2).getFtdz());
                        bdms_fbc_tide_hl_f.setT4(format.parse(gdcbdmsStAstrotdFs.get(3).getYmdh()));
                        bdms_fbc_tide_hl_f.setV4(gdcbdmsStAstrotdFs.get(3).getFtdz());
                        break;
                    default:
                }
                bdms_fbc_tide_hl_fs.add(bdms_fbc_tide_hl_f);
            }

        }
        List<BDMS_FBC_TIDE_HL_F> bdms_fbc_tide_hl_f_List =ToTideList(bdms_fbc_tide_hl_fs);
        for (BDMS_FBC_TIDE_HL_F bdms_fbc_tide_hl_f:bdms_fbc_tide_hl_f_List){
            for (BDMS_ST_ASTROTD_F bdms_st_astrotd_f:gdc_List){
                if (format.format(bdms_fbc_tide_hl_f.getTm()).equals(bdms_st_astrotd_f.getYmdh())){
                    bdms_st_astrotd_f.setHltdmk(bdms_fbc_tide_hl_f.getHltdmk());
                }
            }
        }
        finalDatas.addAll(huorbdmsStAstrotdFs);
        finalDatas.addAll(gdc_List);


        return finalDatas;
    }

    //计算完成后读取数据入库
    public int insert( List<BDMS_ST_ASTROTD_F> bdmsStAstrotdFs ) throws Exception{
        // readToList(getCourseFile()+"\\"+"temp\\"+scheme+"\\SHTIDEcw.lvl","GBK");



        //数据入库
        List<List<BDMS_ST_ASTROTD_F>> batches = splitDataIntoBatches(bdmsStAstrotdFs, 50);
        int total = 0;
        for (List<BDMS_ST_ASTROTD_F> batch : batches) {
            // 插入当前批次的数据
            int res_a= bdms_st_astrotd_fService.insertBatch(batch);
            total += res_a;
        }



        return total;
    }
    public <T> List<List<T>> splitDataIntoBatches(List<T> entities, int batchSize) {
        List<List<T>> batches = new ArrayList<>();
        for (int i = 0; i < entities.size(); i += batchSize) {
            int end = Math.min(entities.size(), i + batchSize);
            List<T> batch = entities.subList(i, end);
            batches.add(batch);

        }
        return batches;
    }
    //高低潮判断
    private static List<BDMS_FBC_TIDE_HL_F> ToTideList(List<BDMS_FBC_TIDE_HL_F> TWChls)
    {
        List<BDMS_FBC_TIDE_HL_F> result = new ArrayList<>();
        if (TWChls == null || TWChls.size() == 0){
            return result;
        }

        for ( BDMS_FBC_TIDE_HL_F item: TWChls)
        {
            String date = format.format(item.getTm());
            BDMS_FBC_TIDE_HL_F D1 = null, D2 = null, D3 = null, D4 = null;

            if (item.getV1()!=null) {
                D1= new BDMS_FBC_TIDE_HL_F();
                D1.setTm(item.getT1());
                D1.setT1(item.getT1());
                D1.setStcd(item.getStcd());
                D1.setV1(item.getV1());
                result.add(D1);
            }
            if (item.getV2()!=null)
            {
                D2= new BDMS_FBC_TIDE_HL_F();
                D2.setTm(item.getT2());
                D2.setT2(item.getT2());
                D2.setStcd(item.getStcd());
                D2.setV2(item.getV2());
                result.add(D2);
            }
            if (item.getV3()!=null)
            {

                D3= new BDMS_FBC_TIDE_HL_F();
                D3.setTm(item.getT3());
                D3.setT3(item.getT3());
                D3.setStcd(item.getStcd());
                D3.setV3(item.getV3());
                result.add(D3);
            }

            if (item.getV4()!=null)
            {
                D4= new BDMS_FBC_TIDE_HL_F();
                D4.setTm(item.getT4());
                D4.setT4(item.getT4());
                D4.setStcd(item.getStcd());
                D4.setV4(item.getV4());
                result.add(D4);
            }


            if (D1 != null && D2 == null && D3 == null && D4 == null){
                continue;
            }

            //判定高低潮

            if (D1.getV1() < D2.getV2())
            {
                //D1 低潮 D2 高潮
                if (D3 == null) {
                    D1.setHltdmk(3);
                } else if (D1.getV1() < D3.getV3())
                {
                    D1.setHltdmk(4);
                    D3.setHltdmk(3);
                }
                else
                {
                    D1.setHltdmk(3);
                    D3.setHltdmk(4);
                }

                if (D4 == null)
                {
                    D2.setHltdmk(1);

                }
                else if (D2.getV2() < D4.getV4())
                {

                    D2.setHltdmk(2);
                    D4.setHltdmk(1);
                }
                else
                {

                    D2.setHltdmk(1);
                    D4.setHltdmk(2);
                }
            }
            else
            {
                //D2 低潮 D1 高潮
                if (D3 == null) {
                    D1.setHltdmk(1);
                } else if (D1.getV1() < D3.getV3())
                {
                    D1.setHltdmk(2);
                    D3.setHltdmk(1) ;
                }
                else
                {

                    D1.setHltdmk(1);
                    D3.setHltdmk(2) ;
                }

                if (D4 == null)
                {
                    D2.setHltdmk(3);
                }
                else if (D2.getV2() < D4.getV4())
                {
                    D2.setHltdmk(3);
                    D4.setHltdmk(4) ;
                }
                else
                {
                    D2.setHltdmk(4);
                    D4.setHltdmk(3) ;
                }
            }
        }
        return result;
    }

}
